package com.sakiko.home1.dao.impl;

import com.sakiko.home1.dao.StudentDao;

import javax.sql.DataSource;
import java.sql.*;

public class StudentDaoImpl implements StudentDao {

    private DataSource dataSource;

    // 属性赋值调用 setXxx  引用类型 ref => 形参 非引用类型 SetXxx -> Xxx就是属性名
    public void setDataSource(DataSource dataSource){
        this.dataSource = dataSource;
    }

    @Override
    public void queryAll() throws SQLException {
        // 2、获取连接
        Connection connection = dataSource.getConnection();
        // 3、数据库 CRUD
        String sql = "select * from sys_user;";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        ResultSet resultSet = preparedStatement.executeQuery();
        // metaData 包含列的信息 列的数量: ColumnCount 列名: ColumnName
        ResultSetMetaData metaData = resultSet.getMetaData();
        int columnCount = metaData.getColumnCount();
        while (resultSet.next()) {
            for (int i = 1; i <= columnCount; i++) {
                String value = resultSet.getString(i); // ColumnIndex or ColumnLabel
                String columnName = metaData.getColumnName(i);
                System.out.println(columnName + "::" + value + " ");
            }
            System.out.println("-----------------------");
        }
        // 4、释放资源
        resultSet.close();
        preparedStatement.close();
        connection.close();
    }
}
